package com.qf.efserver.sport.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qf.common.core.entity.DailyWaterLog;
import com.qf.common.core.entity.Users;
import com.qf.common.core.utils.UserUtils;
import com.qf.efserver.sport.mapper.WaterMapper;
import com.qf.efserver.sport.param.WaterParam;
import com.qf.efserver.sport.service.WaterService;
import com.qf.efserver.user.personaldata.mapper.UsersMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@RequiredArgsConstructor
public class WaterServiceImpl implements WaterService {
    private final WaterMapper waterMapper;
    private final UsersMapper usersMapper;
    @Override
    public WaterParam selectWater() {
        Integer uid = UserUtils.getUid();
        //TODO 查询用户喝水记录
        DailyWaterLog water = waterMapper.selectWater(uid);
        Integer waterNum = water.getWaterNum();
        WaterParam waterParam = new WaterParam();
        // 查询用户标准喝水量
        Users users = usersMapper.selectById(uid);
        waterParam.setWaterNum(waterNum);
        // 设置默认的标准喝水量
        Integer defaultWeight = 60; // 假设的默认体重值，单位为公斤
        Integer standardNum;

        if (users != null && users.getWeight() != null) {
            standardNum = users.getWeight().intValue() * 40; // 计算标准喝水量
        } else {
            standardNum = defaultWeight * 40; // 使用默认值计算
        }

        // 计算用户喝水比例
        // 防止标准水量为零导致除零异常
        waterParam.setWaterRatio(standardNum > 0 ? (waterNum * 100 / standardNum) : 0);

        return waterParam;
    }

    @Override
    public void addWater(Integer waterNum) {
        DailyWaterLog waterLog = waterMapper.selectWater(UserUtils.getUid());
        if (waterLog == null || Objects.isNull(waterNum)){
            DailyWaterLog waterLog1 = new DailyWaterLog();
            waterLog1.setUserId(UserUtils.getUid());
            waterLog1.setWaterNum(waterNum);
            waterMapper.insert(waterLog1);
        }else {
            LambdaUpdateWrapper<DailyWaterLog> updateWrapper = new LambdaUpdateWrapper<DailyWaterLog>()
                    .eq(DailyWaterLog::getId, waterLog.getId())
                    .setSql("water_num = water_num + " + waterNum);
            waterMapper.update(null, updateWrapper);
        }

    }
}
